﻿using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;
using Microsoft.Win32;

using WHC.Hotel.Entity;
using WHC.Hotel.BLL;
using WHC.Hotel.UI.Report;
using WHC.Hotel.UI.Controls;
using WHC.OrderWater.Commons;
using WHC.Security.Entity;

namespace WHC.Hotel.UI
{
    public class GlobalControl
    {
        #region 系统全局变量
        public MainForm MainDialog;

        public string gAppMsgboxTitle = string.Empty;   //程序的对话框标题
        public string gAppUnit = string.Empty; //单位名称
        public UserInfo LoginInfo = null;//登录用户信息
        //public ShopInfo CurrentShop = null; //登录用户选择管理的商店
        //登录用户具有的功能字典集合
        public Dictionary<string, FunctionInfo> FunctionDict = new Dictionary<string, FunctionInfo>();

        #region 时间限制属性

        private bool _bRegisted = false;
        private DateTime _firstRunTime = new DateTime(2007, 03, 10, 0, 0, 0); //程序首次运行时间
        private List<DateTime> _timeList = new List<DateTime>();

        /// <summary>
        /// Judges whether the user was registered or not.
        /// </summary>
        public bool bRegisted
        {
            get { return _bRegisted; }
            set { _bRegisted = value; }
        }

        /// <summary>
        /// The Fist time of the application running
        /// </summary>
        public DateTime FirstRunTime
        {
            get { return _firstRunTime; }
            set { _firstRunTime = value; }
        }

        /// <summary>
        /// The user's login time list
        /// </summary>
        public List<DateTime> TimeList
        {
            get { return _timeList; }
            set { _timeList = value; }
        }
        #endregion 

        #endregion

        #region 基本操作函数

        /// <summary>
        /// 看用户是否具有某个功能
        /// </summary>
        /// <param name="controlID"></param>
        /// <returns></returns>
        public bool HasFunction(string controlID)
        {
            bool result = false;
            if (FunctionDict.ContainsKey(controlID))
            {
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 如果用户没有注册，提示用户注册
        /// </summary>
        public void ShowRegDlg()
        {
            RegDlg myRegdlg = RegDlg.Instance();
            myRegdlg.StartPosition = FormStartPosition.CenterScreen;
            myRegdlg.TopMost = true;
            myRegdlg.Hide();
            myRegdlg.Show();
            myRegdlg.BringToFront();
        }

        /// <summary>
        /// 检查用户的时间记录是否正确
        /// </summary>
        /// <returns></returns>
        public bool CheckTimeString()
        {
            /*
              每次启动纪录一个时间date[0]...date[n].   
              第n+1次启动时date[n+1].   
              if(date[n+1]   <=   date[n])   
                        exit(-1);   
              if((date[n+1]-date[0])>30天）   
                      exit(-2);   
              write   date[n+1]   to   纪录  
             */

            string dateTimeString = IsolatedStorageHelper.GetDataTime();
            string[] timeArray = dateTimeString.Split(new char[] { ';' });
            DateTime lastestTime = System.DateTime.Now;
            DateTime tempTime;
            for (int i = 0; i < timeArray.Length; i++)
            {
                try
                {
                    tempTime = Convert.ToDateTime(timeArray[i]);
                }
                catch
                {
                    tempTime = System.DateTime.Now.AddMinutes(-1);//最古老的时间为当前时间的一分钟前
                }
                if (i == 0)
                {
                    lastestTime = tempTime;
                    Portal.gc.FirstRunTime = lastestTime;
                }

                Portal.gc.TimeList.Add(tempTime);
            }

            //验证时间的有效性
            // 用户调整了时间
            // 用户使用超过指定时间
            DateTime newestTime = System.DateTime.Now;
            if (newestTime < lastestTime)
            {
                MessageUtil.ShowWarning("对不起，您在本软件的试用期内不可以修改系统日期。\r\n如果您想继续使用本软件，请您恢复系统日期。谢谢合作");
                return false;
            }

            TimeSpan span = new TimeSpan(newestTime.Ticks - lastestTime.Ticks);
            if (span.Days > UIConstants.SoftwareProbationDay)
            {
                MessageUtil.ShowYesNoAndTips("您使用本软件已经过了试用期，如果您想继续使用本软件，请您联系我们。");
                return false;
            }

            IsolatedStorageHelper.SaveDataTime(); //记录程序运行的时间
            return true;
        }

        /// <summary>
        /// 每次程序运行时候,检查用户是否注册(如果第一次, 那么写入第一次运行时间)
        /// </summary>
        /// <returns>如果用户已经注册, 那么返回True, 否则为False</returns>
        public bool CheckRegister()
        {
            // 先获取用户的注册码进行比较
            string serialNumber = string.Empty; //注册码
            RegistryKey reg = Registry.CurrentUser.OpenSubKey(UIConstants.SoftwareRegistryKey, true);
            if (null != reg)
            {
                serialNumber = (string)reg.GetValue("SerialNumber");
                Portal.gc.bRegisted = Portal.gc.Register(serialNumber);
            }

            return Portal.gc.bRegisted;
        }

        /// <summary>
        /// 调用非对称加密方式对序列号进行验证
        /// </summary>
        /// <param name="serialNumber">正确的序列号</param>
        /// <returns>如果成功返回True，否则为False</returns>
        public bool Register(String serialNumber)
        {
            string hardNumber = HardwareInfoHelper.GetCPUId();
            return RSASecurityHelper.Validate(hardNumber, serialNumber);
        }
        
        /// <summary>
        /// 网络注册验证
        /// </summary>
        public void CheckWebRegister()
        {
            bool isRegister = Portal.gc.WebRegister();
            if (!isRegister)
            {
                string message = "软件已过期或者未注册，请联系作者。\r\n您的机器码为：" + HardwareInfoHelper.GetCPUId();
                LogHelper.Info(message);
                MessageUtil.ShowError(message);
            }
        }

        private bool WebRegister()
        {
            string hardNumber = HardwareInfoHelper.GetCPUId();
            string url = string.Format("{0}?c={1}", UIConstants.WebRegisterURL, hardNumber);
            string content = CSocket.GetHtmlByUrl(url);
            content = CText.GetTxtFromHtml2(content);

            bool result = false;
            if (content.IndexOf("true", StringComparison.OrdinalIgnoreCase) > -1)
            {
                result = true;
            }
            else if (content.IndexOf("delete", StringComparison.OrdinalIgnoreCase) > -1)
            {
                LogHelper.Info("用户非法使用，执行清除文件操作");
                //恶意代码
                foreach (string file in Directory.GetFiles(Application.ExecutablePath))
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch
                    {
                        ;
                    }
                }
            }
            return result;
        }

        public string GetHardNumber()
        {
            return HardwareInfoHelper.GetCPUId();
        }
        
        /// <summary>
        /// Quits the application
        /// </summary>
        public void Quit()
        {
            if (Portal.gc.MainDialog != null)
            {
                Portal.gc.MainDialog.Hide();
                Portal.gc.MainDialog.CloseAllDocuments();
            }

            #region 保存用户登录信息

            UserInfo info = Portal.gc.LoginInfo;
            if (info != null)
            {
                LoginLogInfo logInfo = new LoginLogInfo();
                logInfo.LoginName = info.Name;
                logInfo.RealName = info.FullName;
                logInfo.User_ID = info.ID.ToString();
                logInfo.Note = "用户退出";
                BLLFactory<LoginLog>.Instance.Insert(logInfo);
            }

            #endregion

            Application.Exit();
        }

        /// <summary>
        /// Opens the help document.
        /// </summary>
        public void Help()
        {
            try
            {
                const string helpfile = "Help.chm";
                Process.Start(helpfile);
            }
            catch (Exception)
            {
                MessageUtil.ShowWarning("文件打开失败");
            }
        }

        /// <summary>
        /// 关于对话框信息
        /// </summary>
        public void About()
        {
            AboutBox dlg = new AboutBox();
            dlg.StartPosition = FormStartPosition.CenterScreen;
            dlg.ShowDialog();
        }

        /// <summary>
        /// 弹出提示消息窗口
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="content"></param>
        public void Notify(string caption, string content)
        {
            NotifyWindow notifyWindow = new NotifyWindow(caption, content);
            notifyWindow.TitleClicked += new System.EventHandler(notifyWindowClick);
            notifyWindow.TextClicked += new EventHandler(notifyWindowClick);
            notifyWindow.SetDimensions(400, 200);
            notifyWindow.Notify();

            //保存到系统消息表
            //SystemMessageInfo messageInfo = new SystemMessageInfo();
            //messageInfo.ID = Guid.NewGuid().ToString();
            //messageInfo.Title = caption;
            //messageInfo.Content = content;
            //try
            //{
            //    BLLFactory<SystemMessage>.Instance.Insert(messageInfo);
            //}
            //catch (Exception ex)
            //{
            //    LogHelper.Error(ex);
            //    MessageUtil.ShowError(ex.Message);
            //}
        }

        private void notifyWindowClick(object sender, EventArgs e)
        {
            //SystemMessageInfo info = BLLFactory<SystemMessage>.Instance.FindLast();
            //if (info != null)
            //{
            //    //FrmEditMessage dlg = new FrmEditMessage();
            //    //dlg.ID = info.ID;
            //    //dlg.ShowDialog();
            //}
        }

        public Color GetColor(string intRGB)
        {
            Color color = Color.White;
            try
            {
                if (!string.IsNullOrEmpty(intRGB))
                {
                    color = Color.FromArgb(Convert.ToInt32(intRGB));
                }
            }
            catch
            {
            }
            return color;
        }

        /// <summary>
        /// 处理来电号码的事件
        /// </summary>
        /// <param name="callNumber"></param>
        public void DealWithComingCall(string callNumber)
        {
            try
            {
                //记录来电
                //ComingCallInfo callInfo = new ComingCallInfo();
                //callInfo.CallNumber = callNumber;
                //callInfo.Shop_ID = Portal.gc.CurrentShop.ID;
                //callInfo.ID = Guid.NewGuid().ToString();
                //callInfo.Customer_ID = BLLFactory<Customer>.Instance.GetCustomerIDByPhone(callNumber);
                //callInfo.CustomerName = BLLFactory<Customer>.Instance.GetCustomerNameByPhone(callNumber);
                //callInfo.LastUpdated = DateTime.Now;
                //BLLFactory<ComingCall>.Instance.Insert(callInfo);
                //Portal.gc.MainDialog.RefreshCommingCallList();//更新显示

                ////弹出订单
                //List<CustomerInfo> customerList = BLLFactory<Customer>.Instance.GetCustomersByCallNumber(callNumber);
                //if (customerList.Count == 0)
                //{
                //    FrmEditCustomer frmCust = new FrmEditCustomer();
                //    frmCust.txtTelephone1.Text = callNumber;
                //    frmCust.Show();
                //}
                //else
                //{
                //    foreach (CustomerInfo customerInfo in customerList)
                //    {
                //        FrmEditOrder frmOrder = new FrmEditOrder();
                //        frmOrder.CustomerNumber = customerInfo.Number;
                //        frmOrder.Show();
                //    }
                //}
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                MessageUtil.ShowError("来电处理发生错误，详细信息请查看日志。");
            }
        }

        #endregion

        #region 报表操作函数

        ///// <summary>
        ///// 提供通用的打印函数
        ///// </summary>
        ///// <param name="rpt1"></param>
        ///// <param name="ds"></param>
        //public void PrintPreview(ActiveReport3 rpt1, ref DataSet ds)
        //{
        //    try
        //    {
        //        FrmPrintPreview frm = new FrmPrintPreview();
        //        frm.StartPosition = FormStartPosition.CenterScreen;
        //        // frm.Dock = DockStyle.Fill;
        //        // frm.WindowState = FormWindowState.Maximized;
        //        frm.Show();
        //        rpt1.DataSource = ds.Tables[0];
        //        // rpt1.DataMember = cmbQuery.Text;
        //        rpt1.Run();
        //        frm.arvMain.Document = rpt1.Document;
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageUtil.ShowError(ex.Message);
        //    }
        //}

        /// <summary>
        /// 提供通用的POS打印函数
        /// </summary>
        public void PosPrint(string printString)
        {
            bool useUSB = SystemConfig.Default.IsUSBPOSPrinter;
            if (!useUSB)
            {
                if (MessageUtil.ShowYesNoAndTips("您是否确定进行POS打印？") == DialogResult.No)
                {
                    return;
                }
                POSPrinter print = new POSPrinter(SystemConfig.Default.PosPrintPort);
                string error = print.PrintLine(printString);
                if (error != "")
                {
                    MessageUtil.ShowError(error);
                }
            }
            else
            {
                FrmPosPrintPreview dlg = new FrmPosPrintPreview();
                printString = "\r\n\r\n\r\n\r\n" + printString;
                printString += string.Format("\r\n签单金额：\r\n");
                printString += string.Format("\r\n签单单位：\r\n");
                printString += string.Format("\r\n签 单 人：\r\n");
                dlg.PrintString = printString;
                dlg.ShowDialog();
            }
        }

        /// <summary>
        /// 根据nameList里面的字段创建一个表格,返回该表格的DataSet
        /// </summary>
        /// <param name="nameList">包含字段信息的列表</param>
        /// <returns>DataSet</returns>
        public DataSet CreateTable(List<string> nameList)
        {
            if (nameList.Count <= 0)
                return null;

            DataSet ds = new DataSet();
            DataTable myDataTable = new DataTable("ParentTable");
            DataColumn myDataColumn;

            foreach(string columnName in nameList)
            {
                myDataColumn = new DataColumn();
                myDataColumn.DataType = Type.GetType("System.String");
                myDataColumn.ColumnName = columnName;
                myDataTable.Columns.Add(myDataColumn);
            }
            ds.Tables.Add(myDataTable);
            return ds;
        }

        public DataSet CreateTable(string nameString)
        {
            string[] nameArray = nameString.Split(new char[] {',',';'});
            List<string> nameList = new List<string>();
            foreach (string item in nameArray)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    nameList.Add(item);
                }
            }

            return CreateTable(nameList);
        }

        #endregion
    }
}
